package com.xhl.oauth2.config.security;

import com.xhl.oauth2.modules.admin.service.SysUserService;
import com.xhl.oauth2.modules.admin.vo.SysUserVo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName: SysUserDetailService
 * @Description: 权限集合校验和获取添加
 * @Author:     lisk
 * @Date:        2023-08-18 15:34
 * @Version: 1.0
 */
@Component
public class SysUserDetailService implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        ////数据库查询 看用户是否存在
        SysUserVo oneUser = sysUserService.selectOneUserByUsername(s);
        String encodedPassword = oneUser.getPassword();
        Collection<GrantedAuthority> collection = new ArrayList<>();//权限集合
        //用户权限：需要加 ROLE_
        List<String> roles = oneUser.getRoles();
        for (String role : roles) {
            //hasAnyRole 校验要加ROLE_ 前缀
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + role);
            collection.add(grantedAuthority);
        }
        //增加用户的userid
        SecurityUser user = new SecurityUser(s,encodedPassword,collection);
        user.setUserId(oneUser.getUserId());
        return user;
    }
}
